package org.ctstudio.common.utils;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class SqlDateEditor extends PropertyEditorSupport {
  private static final DateFormat DEFAULT_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

  private DateFormat dateFormat;

  public SqlDateEditor(DateFormat dateFormat) {
    this.dateFormat = dateFormat == null ? DEFAULT_FORMAT : dateFormat;
  }

  public SqlDateEditor() {
    this(null);
  }

  public void setAsText(String text) throws IllegalArgumentException {
    if (text == null || text.length() == 0) {
      setValue(null);
    } else {
      setValue(java.sql.Date.valueOf(text));
    }
  }

  public String getAsText() {
    java.sql.Date value = (java.sql.Date) getValue();
    return value != null ? this.dateFormat.format(value) : "";
  }
}